<template>
	<view class="profile-page">
		<!-- 用户信息区 -->
		<view class="user-header">
			<image class="avatar" :src="user.avatar"></image>
			<view class="user-info">
				<view class="name-row">
					<text class="username">{{ user.name }}</text>
					<image class="edit-icon" src="/static/black.png" @click="toMine"></image>
				</view>
				<text class="birthday">{{ user.birthday }}</text>
			</view>
		</view>

		<!-- 我的档案 -->
		<view class="section">
			<view class="section-header">
				<view style="display: flex;align-items: center;">
					<view class="header-marker"></view>
					<text class="header-title">我的档案</text>
				</view>

			</view>
			<view class="record-group">
				<!-- 修改这里：添加点击事件 -->
				<view class="record-item" v-for="(item, idx) in recordItems"
					@click="item.text === '挂号订单' ? toMyBooking() : tobingli()" :key="idx">
					<image class="record-icon" :src="item.icon"></image>
					<text class="record-text">{{ item.text }}</text>
				</view>
			</view>
		</view>

		<!-- 个人健康数据 -->
		<view class="section">
			<view class="section-header" style="border-bottom: 3rpx solid #ECECEC;padding-bottom: 15rpx;">
				<view style="display: flex;align-items: center;">
					<view class="header-marker"></view>
					<text class="header-title">个人健康数据</text>
					<text class="data-date">{{ formatDate(healthData.update_time) }}</text>
				</view>

				<image class="edit-icon" src="/static/bi.png" @click="toUpdate"></image>
			</view>
			<view class="data-table">
				<view class="data-row">
					<text class="label">身高（cm）</text>
					<text class="value">{{ healthData.height || '--' }}cm</text>
				</view>
				<view class="data-row">
					<text class="label">体重（kg）</text>
					<text class="value">{{ healthData.weight || '--' }}kg</text>
				</view>
				<view class="data-row">
					<text class="label">血压（mmHg）</text>
					<text class="value">{{ healthData.blood_ressure || '--' }}mmHg</text>
				</view>
				<view class="data-row">
					<text class="label">血糖（mmol/L）</text>
					<text class="value">餐前 {{ healthData.blood_sugar || '--' }}mmol/L</text>
				</view>
			</view>
		</view>

		<!-- 功能菜单 -->
		<view class="function-menu">
			<view class="menu-item" v-for="(item, idx) in functionItems" :key="idx" @click="handleAction(item)">
				<image class="menu-icon" :src="item.icon"></image>
				<text class="menu-text">{{ item.text }}</text>
				<image class="arrow-icon" src="/static/right.png"></image>
			</view>
		</view>
	</view>
</template>

<script setup lang="ts">
import { onMounted, ref, onUnmounted } from 'vue';
import { onShow } from '@dcloudio/uni-app'
// 数据类型定义
interface User {
	avatar: string
	name: string
	birthday: string
}
interface RecordItem {
	icon: string
	text: string
}
interface HealthDataItem {
	label: string
	value: string
	prefix?: string
}
interface FunctionItem {
	icon: string
	text: string
}

const toMyBooking = () => {
	uni.navigateTo({
		url: '/pages/myBooking/myBooking'
	})
}

const toUpdate = () => {
	uni.navigateTo({
		url: '/pages/update/update'
	})
}


// 模拟数据（需替换实际图标路径）
const user = ref<User>({
	avatar: '/static/doctor.png',   // 用户头像
	name: '用户名',
	birthday: '1996-11-02'
})

const recordItems = ref<RecordItem[]>([
	{ icon: '/static/dan.png', text: '挂号订单' },  // 挂号订单图标
	{ icon: '/static/bing.png', text: '过往病史' } // 过往病史图标
])

const functionItems = ref<FunctionItem[]>([
	{ icon: '/static/wei.png', text: '地址管理' },
	{ icon: '/static/yi.png', text: '医生入驻' },
	{ icon: '/static/men.png', text: '退出账号' },
	{ icon: '/static/fei.png', text: '关于' }
])

// 退出逻辑
const handleAction = (item: FunctionItem) => {
	if (item.text === '退出账号') {
		uni.showModal({
			title: '提示',
			content: '确定要退出登录吗？',
			success: (res) => {
				if (res.confirm) {
					uni.removeStorageSync('token')
					uni.reLaunch({ url: '/pages/login/login' })
				}
			}
		})
	} else if (item.text === '医生入驻'){
		uni.navigateTo({
			url: '/pages/doctor/doctor'
		})
	}
}

// 核心修改：将userInfo定义为响应式ref变量
const userInfo = ref(uni.getStorageSync('userInfo') || {});

// 健康数据
const healthData = ref({
	height: '',
	weight: '',
	blood_ressure: '',
	blood_sugar: '',
	update_time: ''
});

const formatDate = (dateString) => {
	if (!dateString) return '';
	// 只取日期部分（YYYY-MM-DD）
	return dateString.split('T')[0];
};

// 获取健康数据的函数
const fetchHealthData = () => {
	const token = uni.getStorageSync('token');
	const currentUser = uni.getStorageSync('userInfo')
	uni.request({
		url: `http://localhost:3010/user/health?uid=${currentUser.uid}`,
		method: 'GET',
		header: {
			'Authorization': `Bearer ${token}`,
		},
		success: (res: any) => {
			console.log('健康数据请求结果:', res.data);
			if (res.data && res.data.data) {
				healthData.value = {
					height: res.data.data[0].height,
					weight: res.data.data[0].weight,
					blood_ressure: res.data.data[0].blood_ressure,
					blood_sugar: res.data.data[0].blood_sugar,
					update_time: res.data.data[0].update_time
				};
			}
		}
	});
};

// 页面挂载时初始化数据
onMounted(() => {
	fetchHealthData();
	// 监听全局用户信息更新事件
	uni.$on('userInfoUpdated', handleUserInfoUpdate);
	updateUserInfo()
});

// 核心修改：页面显示时刷新数据（从存储重新读取）
onShow(() => {
	fetchHealthData();
	// 重新从本地存储获取最新用户信息
	userInfo.value = uni.getStorageSync('userInfo') || {};
	updateUserInfo()
});

// 更新用户信息的函数
const updateUserInfo = () => {
    userInfo.value = uni.getStorageSync('userInfo') || {};
    user.value.avatar = userInfo.value.avatar || '/static/doctor.png'
    user.value.name = userInfo.value.name || '用户名'
    user.value.birthday = userInfo.value.birthday || '1996-11-02'
}


// 处理全局事件的回调函数
const handleUserInfoUpdate = (updatedUserInfo) => {
	userInfo.value = updatedUserInfo;
	updateUserInfo()
};

// 页面卸载时移除事件监听（防止内存泄漏）
onUnmounted(() => {
	uni.$off('userInfoUpdated', handleUserInfoUpdate);
});

// 跳转到健康数据编辑页
const toHealth = () => {
	uni.navigateTo({
		url: `/pages/myupdate/myupdate?data=${encodeURIComponent(JSON.stringify(healthData.value))}`
	})
};

const tobingli = () => {
	uni.navigateTo({
		url: '/pages/mybingli/mybingli'
	})
}

// 跳转到用户信息编辑页
const toUser = () => {
	uni.navigateTo({
		url: '/pages/my/myDetails'
	})
};

const toMine = () => {
	uni.navigateTo({
		url: '/pages/mineUpdate/mineUpdate'
	})
}

</script>

<style scoped lang="scss">
.profile-page {
	background-color: #e1e1e1;
	min-height: 100vh;
	padding: 30rpx;
	padding-top: 90rpx;
	box-sizing: border-box;

	// 用户信息区
	.user-header {
		display: flex;
		align-items: center;
		margin-bottom: 60rpx;

		.avatar {
			width: 140rpx;
			height: 140rpx;
			border-radius: 50%;
			margin-right: 25rpx;
		}

		.user-info {
			display: flex;
			flex-direction: column;

			.name-row {
				display: flex;
				align-items: center;
				margin-bottom: 10rpx;

				.username {
					font-size: 48rpx;
					font-weight: bold;
					color: #333;
				}

				.edit-icon {
					width: 66rpx;
					height: 66rpx;
					margin-left: 15rpx;
				}
			}

			.birthday {
				font-size: 28rpx;
				color: #999;
			}
		}
	}

	// 通用板块头
	.section {
		background: #FFF;
		border-radius: 20rpx;
		padding: 25rpx;
		margin-bottom: 35rpx;

		.section-header {
			display: flex;
			align-items: center;
			margin-bottom: 25rpx;
			justify-content: space-between;

			.header-marker {
				width: 6rpx;
				height: 32rpx;
				background: #00ff06;
				margin-right: 12rpx;
			}

			.header-title {

				font-size: 32rpx;
				font-weight: bold;
				color: #757575;
			}

			.data-date {
				margin-left: 30rpx;
				font-size: 24rpx;
				color: #999;
				margin-right: 25rpx;
			}

			.edit-icon {
				width: 66rpx;
				height: 66rpx;
			}
		}
	}

	// 我的档案 - 核心调整：左对齐 + 间距
	.record-group {
		display: flex;
		flex-direction: row;
		align-items: center;
		padding-left: 10rpx; // 左对齐偏移

		.record-item {
			display: flex;
			flex-direction: column;
			align-items: center;
			margin-right: 50rpx; // 项目间距

			.record-icon {
				width: 64rpx;
				height: 64rpx;
				margin-bottom: 12rpx;
			}

			.record-text {
				font-size: 26rpx;
				color: #999;
			}
		}
	}

	// 健康数据表格
	.data-table {
		.data-row {
			display: flex;
			justify-content: space-between;

			&:last-child {
				border-bottom: none;
			}

			.data-label {
				font-size: 28rpx;
				color: #ababab;
			}

			.data-value {
				font-size: 28rpx;
				color: #ababab;

				.prefix {
					color: #ababab;
					margin-right: 8rpx;
				}
			}
		}
	}

	// 功能菜单
	.function-menu {
		background: #FFF;
		border-radius: 20rpx;

		.menu-item {
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 25rpx;
			border-bottom: 1px solid #ECECEC;

			&:last-child {
				border-bottom: none;
			}

			.menu-icon {
				width: 60rpx;
				height: 60rpx;
				margin-right: 16rpx;
			}

			.menu-text {
				flex: 1;
				font-size: 34rpx;
				color: #333;
			}

			.arrow-icon {
				width: 48rpx;
				height: 48rpx;
				color: #00CC71;
				font-weight: 600;
			}
		}
	}
}
</style>